import { useState, useMemo, forwardRef, useImperativeHandle } from 'react'

const VoteMain = function VoteMain(props, ref) {
    // 定义状态
    let [supNum, setSupNum] = useState(10),
        [oppNum, setOppNum] = useState(5)

    // 计算支持比率
    let ratio = useMemo(() => {
        let result = '- -',
            total = supNum + oppNum
        if (total > 0) {
            result = (supNum / total * 100).toFixed(2) + '%'
        }
        return result
    }, [supNum, oppNum])

    // 修改状态的方法
    const change = (type) => {
        console.log('AAA')
        if (type === 'sup') {
            setSupNum(supNum + 1)
            return
        }
        setOppNum(oppNum + 1)
    }

    // 暴露信息给外面使用
    useImperativeHandle(ref, () => {
        return {
            supNum,
            oppNum,
            change
        }
    })

    return <div className="main-box">
        <p>支持人数：{supNum} 人</p>
        <p>反对人数：{oppNum} 人</p>
        <p>支持比率：{ratio}</p>
    </div>
}

export default forwardRef(VoteMain)